import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import {staticRoutes} from '@/router/routes'
import type {reqUserInfoReturnType, reqLoginParamType} from '@/api/userInfo'
import {requestLogin,requestUserInfo,requestLogOut} from '@/api/userInfo'
import type { RouteRecordRaw } from 'vue-router';


/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */

//小store仓库数据类型
export interface UserInfoState{
  token:string,
  userInfo:reqUserInfoReturnType,
  menuRoutes:RouteRecordRaw[]
}

export const useUserInfoStore = defineStore('userInfo', {
	state: (): UserInfoState => ({
    token: getToken() as string || '',
    userInfo:{
      routes: [],
      buttons: [],
      roles: [],
      name: '',
      avatar: '',
    },
    //静态路由表，侧边栏拿路由表遍历侧边栏元素
    menuRoutes: staticRoutes
  }),

	actions: {
    //登录请求函数
    async login (loginParam:reqLoginParamType) {
    
        try {
          //发送登录请求
          const re = await requestLogin(loginParam)
          //获取token
          this.token = re.token
          //设置token到本地,数据持久化
          setToken(this.token)
        } catch (e) {
          //请求失败，谁调用谁处理
          return Promise.reject(e)
        }
     },
     //获取用户信息请求
    async getInfo () {
      try {
        //发送请求
        const re = await requestUserInfo()
        //获取用户信息
        this.userInfo = re
      } catch (e) {
        return Promise.reject(e)
      }  
    },
    //退出登录请求
    async getLogOut() {
      try {
        //发送请求
        await requestLogOut()
        //重置信息
        this.reset()
      } catch (e) {
        return Promise.reject(e)
      }
    },
    //重置信息
    reset () {
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.userInfo = {
        routes: [],
        buttons: [],
        roles: [],
        name: '',
        avatar: ''
      }
    },
	},
});
